// Copyright (c) 2024 NutPi. All rights reserved.
// Author: NutPi
// Website: https://nutpi.com
// WeChat: nutpi

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/article.dart';
import '../services/rss_service.dart';
import 'package:flutter/foundation.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final RssService _rssService = RssService();
  List<Article> _articles = [];
  bool _isLoading = false;
  String? _error;

  @override
  void initState() {
    super.initState();
    debugPrint('HomePage: 初始化页面');
    _loadArticles();
  }

  Future<void> _loadArticles() async {
    if (_isLoading) {
      debugPrint('HomePage: 已有加载任务正在进行中，跳过此次请求');
      return;
    }

    debugPrint('HomePage: 开始加载文章列表');
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      debugPrint('HomePage: 调用 RssService 获取文章数据');
      final articles = await _rssService.fetchArticles();
      debugPrint('HomePage: 成功获取文章数据，共 ${articles.length} 篇');
      setState(() {
        _articles = articles;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('HomePage: 加载文章失败 - $e');
      setState(() {
        _error = e.toString();
        _isLoading = false;
      });
    }
  }

  Future<void> _openArticle(String url) async {
    debugPrint('HomePage: 尝试打开文章链接 - $url');
    final uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      debugPrint('HomePage: 打开文章链接');
      await launchUrl(uri);
    } else {
      debugPrint('HomePage: 无法打开文章链接');
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法打开链接: $url')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('HomePage: 构建页面 UI');
    return Scaffold(
      appBar: AppBar(
        title: const Text('掘金 RSS'),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: _loadArticles,
        child: _error != null
            ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(_error!, style: const TextStyle(color: Colors.red)),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _loadArticles,
                      child: const Text('重试'),
                    ),
                  ],
                ),
              )
            : _isLoading && _articles.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : ListView.builder(
                    itemCount: _articles.length,
                    itemBuilder: (context, index) {
                      final article = _articles[index];
                      return Card(
                        margin: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 8,
                        ),
                        child: InkWell(
                          onTap: () => _openArticle(article.link),
                          child: Padding(
                            padding: const EdgeInsets.all(16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  article.title,
                                  style: const TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  article.description,
                                  maxLines: 3,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                const SizedBox(height: 8),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Expanded(
                                      child: Text(
                                        article.author,
                                        style: TextStyle(
                                          color: Colors.grey[600],
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                    const SizedBox(width: 8),
                                    Expanded(
                                      child: Text(
                                        article.pubDate,
                                        style: TextStyle(
                                          color: Colors.grey[600],
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                        textAlign: TextAlign.right,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  ),
      ),
    );
  }
}
